package com.carrentalplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrentalplatform.mapper.UserMapper;
import com.carrentalplatform.model.User;
import com.carrentalplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User login(String username, String password) {
        // 查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = this.getOne(queryWrapper);
        
        // 校验密码
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(User user) {
        // 判断用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (this.count(queryWrapper) > 0) {
            return false;
        }
        
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 设置默认参数
        user.setStatus(1);
        user.setCreditScore(100);
        
        return this.save(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCreditScore(Long userId, Integer score) {
        User user = this.getById(userId);
        if (user == null) {
            return false;
        }
        
        // 更新信用分
        int newScore = user.getCreditScore() + score;
        // 信用分范围 0-100
        newScore = Math.max(0, Math.min(100, newScore));
        
        user.setCreditScore(newScore);
        return this.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean verifyIdentity(Long userId, String realName, String idCard) {
        User user = this.getById(userId);
        if (user == null) {
            return false;
        }
        
        // 更新实名信息
        user.setRealName(realName);
        user.setIdCard(idCard);
        
        return this.updateById(user);
    }
    
    @Override
    public List<User> getAllUsers() {
        return this.list();
    }
    
    @Override
    public User findById(Long id) {
        return this.getById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user) {
        User existingUser = this.getById(user.getId());
        if (existingUser == null) {
            return false;
        }
        
        // If password is provided and changed, encode it
        if (user.getPassword() != null && !user.getPassword().isEmpty() 
                && !passwordEncoder.matches(user.getPassword(), existingUser.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            // Keep the original password
            user.setPassword(existingUser.getPassword());
        }
        
        return this.updateById(user);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long id) {
        return this.removeById(id);
    }
} 